/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cnpm;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Chi Cong
 */
public class Connect {
    private String host="";
    private String port="";
    private String user="";
    private String pass="";
    private String database="";
    private Connection cn=null;
    private Statement st=null;
    private ResultSet rs=null;
    
    void LoadConfig()
    {
        host="QUAN-4D14CB4ABD";
        port="1433";
        user="sa";
        pass="123";
        database="QL10";
        
    }
    
    public void testDriver(){
        LoadConfig();
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public Connection getConnect(){
        if(this.cn==null)
        {
         testDriver();
         String url = "jdbc:sqlserver://" + this.host + ":" + this.port + ";databaseName=" + this.database;
        try {
                 this.cn = DriverManager.getConnection(url, this.user, this.pass);
       
            } catch (SQLException ex) {
                Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
            
            }
        
        }
        return this.cn;
    }
    
    public Statement getStatement() throws SQLException
    {
            if(this.st==null || this.st.isClosed()){
        this.st = (Statement) getConnect().createStatement();
    }
    return this.st;
}
        public ResultSet excuteQuery(String Query) {
        try {
            this.rs = getStatement().executeQuery(Query);
        } catch (SQLException ex) {
            Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return this.rs;
    }
    
    public int executeUpdate(String Query) throws SQLException{
        int res = Integer.MIN_VALUE;
        try {
            res = getStatement().executeUpdate(Query);
        } catch (SQLException ex) {
            Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            this.Close();
        }
        return res;
    }
       
     public void Close() throws SQLException{
         if (this.rs !=null){
             if(!this.rs.isClosed()){
                 this.rs.close();
             }
             this.rs = null;
         }
         if (this.st !=null){
             if(!this.st.isClosed()){
                 this.st.close();
             }
             this.st = null;
         }
         if (this.cn !=null){
             if(!this.cn.isClosed()){
                 this.cn.close();
             }
             this.cn = null;
         }
     }
}